<template>
  <a-layout style="min-height: 100vh">
    <a-layout-sider v-model:collapsed="collapsed" collapsible>
      <div class="logo" />
      <a-menu v-model:selectedKeys="selectedKeys" theme="dark" mode="inline">
        <a-menu-item v-for="(item, index) in newNavList[0].children" :key="index + 1" @click="menuClick(item, index + 1)">
          <pie-chart-outlined />
          <span>{{ item.meta.title }}</span>
        </a-menu-item>
      </a-menu>
    </a-layout-sider>
    <a-layout>
      <a-layout-content style="margin: 0 16px">
        <div style="display: flex; justify-content: space-between">
          <a-breadcrumb style="margin: 16px 0">
            <a-breadcrumb-item v-for="(item, index) in breadcrumbData" :key="index">{{ item }}</a-breadcrumb-item>
          </a-breadcrumb>
          <div style="display: flex; align-items: center">
            <div @click="loginOut">退出登录</div>
          </div>
        </div>
        <div :style="{ padding: '24px', background: '#fff', minHeight: '360px' }">
          <router-view />
        </div>
      </a-layout-content>
    </a-layout>
  </a-layout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import Cookies from 'js-cookie'

const selectedKeys = ref([1])
const collapsed = ref(false)
const router = useRouter()
const navList = ref([])
navList.value = router.getRoutes()
const newNavList = ref([])
navList.value.forEach(item => {
  if (item.children && item.children.length > 0) {
    newNavList.value.push(item)
  }
})
onMounted(() => {
  if (Cookies.get('selectedKeys')) {
    selectedKeys.value = [Number(Cookies.get('selectedKeys'))]
    menuClick(newNavList.value[0].children[selectedKeys.value - 1], Number(Cookies.get('selectedKeys')))
  }
})
const routerUrl = ref('/home/homePage')
//默认跳到首页
router.push({ path: routerUrl.value })
//菜单点击事件
function menuClick(item, index) {
  Cookies.set('selectedKeys', index)
  let url = `/home/${item.name}`
  routerUrl.value = url
  router.push({ path: url })
  setBreadcrumbData()
}
const breadcrumbData = ref([])
function setBreadcrumbData() {
  let array = routerUrl.value.split('/')
  breadcrumbData.value = array.filter(value => value !== '')
}
setBreadcrumbData()
//退出登录操作
async function loginOut() {
  await router.push({ path: '/' })
}

</script>

<style scoped>
#components-layout-demo-side .logo {
  height: 32px;
  margin: 16px;
  background: rgba(255, 255, 255, 0.3);
}

.site-layout .site-layout-background {
  background: #fff;
}
[data-theme='dark'] .site-layout .site-layout-background {
  background: #141414;
}
</style>
